<?php

/*
 * Copyright (C) 2014 koodo@qq.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

/**
 * System Super Class Controller
 */
class Controller {

    // 模板引擎句柄
    protected $Smarty;
    // ActionName
    private $Action;
    // ControllerName
    private $ControllerName;
    // QueryString
    private $QueryString;
    // currentURI
    public $uri;

    const VPAR_RES_GET = 0;
    const VPAR_RES_POST = 1;
    const VPAR_RES_COOKIE = 2;

    public function __construct($ControllerName, $Action, $QueryString) {
        global $config;
        // Params
        $this->ControllerName = $ControllerName;
        $this->Action = $Action;
        $this->QueryString = $QueryString;
        // Smarty
        $this->Smarty = new Smarty();
        // Smarty TemplateDir
        $this->Smarty->setTemplateDir(dirname(__FILE__) . DIRSEP . '..' . DIRSEP . $config->tpl_dir . DIRSEP);
        // Smarty CompileDir
        $this->Smarty->setCompileDir(dirname(__FILE__) . DIRSEP . '..' . DIRSEP . $config->tpl_dir . DIRSEP . '_compile' . DIRSEP);
        // css version
        $this->Smarty->assign('cssversion', time());
        // root
        $this->Smarty->assign('docroot', '/wshop/');

        $this->loadModel('Util');
    }

    /**
     * 模板渲染
     */
    public function show($tpl_name = false) {
        /**
         * 模板文件名判断，必须区分控制器目录。
         * 如果指定目录，则查找view目录
         */
        $tpl_name = !$tpl_name ? $this->Action : $tpl_name;
        // 带目录路径
        if (preg_match('/\//', $tpl_name)) {
            $this->Smarty->display($tpl_name);
        } else {
            $this->Smarty->display(strtolower($this->ControllerName) . DIRSEP . strtolower($tpl_name) . '.tpl');
        }

        // 流量监控
        if ($this->ControllerName !== 'Wdmin' && strpos('ajax', $this->Action) === false) {
            $this->loadModel('Db');
            $this->Db->query(sprintf("INSERT INTO `pageview_records` (`page`,`ip`,`openid`,`time`) VALUES ('%s','%s','%s',NOW());", $this->uri, $this->getIp(), $_COOKIE['uopenid']));
        }
    }

    /**
     * 加载模型
     * @param type $modelName
     * @return stdClass
     */
    protected function loadModel($modelName) {
        if (!isset($this->$modelName)) {
            $this->$modelName = new $modelName();
            $this->$modelName->linkController($this);
        }
        return $this->$modelName;
    }

    /**
     * 判断是否在微信浏览器
     * @return type
     */
    final public static function inWechat() {
        return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false;
    }

    /**
     * 获取用户openid
     * @return boolean | object
     */
    protected function getOpenId($redirect_uri = false, $both = false) {
        #unset($_COOKIE['uopenid']);
        #setcookie("uopenid", 'od2ZEuGcj5xSuk_YJuSpJ2wPsKp0', time() + 3600);
        $Openid = null;
        $AccessToken = null;
        if (isset($_COOKIE['uopenid']) || isset($_COOKIE['uaccesstoken'])) {
            $Openid = $_COOKIE['uopenid'];
            $AccessToken = $_COOKIE['uaccesstoken'];
            $this->refreshOpenId($Openid, $AccessToken);
        } else {
            if ($this->inWechat()) {
                $redirect_uri = !$redirect_uri ? "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] : $redirect_uri;
                $this->loadModel('WechatSdk');
                $AccessCode = WechatSdk::getAccessCode($redirect_uri, "snsapi_base");
                if ($AccessCode !== FALSE) {
                    // 获取到accesstoken和openid
                    $Result = WechatSdk::getAccessToken($AccessCode);
                    $Openid = $Result->openid;
                    $AccessToken = $Result->access_token;
                    // cookie持久1小时
                    $this->refreshOpenId($Openid, $AccessToken);
                    unset($Result);
                }
                unset($AccessCode);
            } else {
                return false;
            }
        }
        if ($both) {
            $ret = new stdClass();
            $ret->openid = $Openid;
            $ret->accesstoken = $AccessToken;
            return $ret;
        }
        return $Openid;
    }

    /**
     * 持久cookie
     * @param type $Openid
     * @param type $AccessToken
     */
    private function refreshOpenId($Openid, $AccessToken) {
        setcookie("uopenid", $Openid, time() + 36000);
        setcookie("uaccesstoken", $AccessToken, time() + 36000);
    }

    /**
     * include path
     */
    protected function add_include_path($path) {
        set_include_path($path . get_include_path());
    }

    /**
     * getIPaddress
     * @return type
     */
    final public function getIp() {
        return $this->Util->getIp();
    }

    final public function log($content) {
        $this->Db->query("INSERT INTO `log` (`logcont`) VALUES ('$content');");
    }

    /**
     * print json from array
     * @param type $arr
     */
    final public function echoJson($arr) {
        print_r(json_encode($arr));
    }

    public function getShopSettings() {
        $ret = new stdClass();
        $settings = $this->Db->query("SELECT `setting_key`,`setting_value` FROM `shops_settings` WHERE shop_id = 0;");

        foreach ($settings as $key => $st) {
            $ret->$st['setting_key'] = $st['setting_value'];
        }
        return $ret;
    }

    /**
     * 获取GET参数
     * @param type $name
     * @param type $default
     * @return type
     */
    public function pGet($name = false, $default = 0) {
        return $this->getpostV($name, $default, $_GET);
    }

    /**
     * 获取POST参数
     * @param type $name
     * @param type $default
     * @return type
     */
    public function pPost($name = false, $default = 0) {
        return $this->getpostV($name, $default, $_POST);
    }

    /**
     * 
     * @param type $name
     * @param type $default
     * @return type
     */
    public function pCookie($name = false, $default = 0) {
        return $this->getpostV($name, $default, $_COOKIE);
    }

    private function getpostV($name, $default = 0, $retSet = array()) {
        if (!$name || empty($retSet))
            return false;
        if (($isGet && !isset($retSet[$name]))) {
            return $default;
        } else {
            $name = $this->Util->xssFilter($name);
            return $this->Util->xssFilter($retSet[$name]);
        }
    }

    /**
     * report error
     * @param type $msg
     * @param type $filename
     */
    final public function reportError($msg, $filename) {
        include_once(dirname(__FILE__) . "/../models/WechatSdk.php");
        $stoken = WechatSdk::getServiceAccessToken();
        Messager::sendText($stoken, DEVREPORT_OPENID, date("Y-m-d h:i:sa") . ' 错误信息' . $msg . ' 文件路径：' . $filename);
    }

}
